package org.cfk.asyncdownloadtutorial.downloadhandler;

import lombok.Data;
import org.cfk.asyncdownloadtutorial.annotation.AsyncDownloadJobWorker;
import org.cfk.asyncdownloadtutorial.dto.CsvDownloadRequest;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Component
public class CsvDownloadHandler {

    /**
     * CSV文件导出处理方法
     * 
     * @param params 导出参数
     * @param file 输出文件
     */
    private final Random random = new Random();
    private final String[] FIRST_NAMES = {"张", "李", "王", "刘", "陈", "杨", "赵", "黄", "周", "吴"};
    private final String[] LAST_NAMES = {"伟", "芳", "娜", "秀英", "敏", "静", "丽", "强", "磊", "军"};
    
    @AsyncDownloadJobWorker("csv")
    public void handleCsvDownload(CsvDownloadRequest params, File file) throws IOException {
        try (FileWriter writer = new FileWriter(file)) {
            // 写入CSV头部
            writer.write(String.join(",", params.getHeaders()) + "\n");
            
            // 生成并写入随机数据行
            for (int i = 0; i < params.getRowCount(); i++) {
                List<String> row = generateRandomRow(params.getColumnTypes());
                writer.write(String.join(",", row) + "\n");
            }
        }
    }
    
    private List<String> generateRandomRow(List<String> columnTypes) {
        List<String> row = new ArrayList<>();
        for (String type : columnTypes) {
            row.add(generateRandomValue(type));
        }
        return row;
    }
    
    private String generateRandomValue(String type) {
        switch (type.toLowerCase()) {
            case "number":
                return String.valueOf(random.nextInt(10000));
            case "decimal":
                return String.format("%.2f", random.nextDouble() * 1000);
            case "date":
                return LocalDate.now().minusDays(random.nextInt(365))
                        .format(DateTimeFormatter.ISO_DATE);
            case "datetime":
                return LocalDateTime.now().minusDays(random.nextInt(365))
                        .format(DateTimeFormatter.ISO_DATE_TIME);
            case "name":
                return LAST_NAMES[random.nextInt(LAST_NAMES.length)] + 
                       FIRST_NAMES[random.nextInt(FIRST_NAMES.length)];
            case "boolean":
                return String.valueOf(random.nextBoolean());
            default:
                return "数据" + random.nextInt(100);
        }
    }

}